<template>
	<div>
		<div class="user-container">
			<!-- 功能栏 -->
			<el-form :inline="true" :model="searchMap">
				<el-form-item>
					<el-button @click="handleAdd" type="primary" plain>分享</el-button>
				</el-form-item>
			</el-form>

			<!-- table数据 -->
			<el-table ref="multipleTable" :data="tableData" @selection-change="handleSelectionChange"
				@sort-change="sortchange" border tooltip-effect="dark" style="width: auto; overflow: hidden" :row-key="
					(row) => {
						return row.id;
					}
				">
				<el-table-column type="selection" width="40" :reserve-selection="true">
				</el-table-column>
				<el-table-column type="index" label="序号" width="50">
				</el-table-column>
				<el-table-column prop="userName" label="用户名"> </el-table-column>
				<el-table-column prop="name" label="所属公司"> </el-table-column>
				<el-table-column prop="phone" label="电话"> </el-table-column>
				<!-- <el-table-column prop="email" label="电子邮箱"> </el-table-column> -->

				<el-table-column prop="lastLoginTime" label="最后登录时间">
				</el-table-column>
				<el-table-column label="编辑操作" width="350">
					<template slot-scope="scope">
						<el-button type="primary" size="small" @click="handleEditOrgan(scope.row)">网点</el-button>
						<el-button type="primary" size="small" @click="handleManageArea(scope.row)">区域</el-button>

						<el-button type="primary" size="small" @click="handleDelete(scope.row)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination @size-change="handleSizeChange" @current-change="handlePageChange" :current-page="currentPage"
				:page-sizes="[10, 20, 30, 40]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
				:total="total" style="text-align: right">
			</el-pagination>

			<!-- 新增员工 -->
			<el-dialog class="add-user-dia" :title="isAddNew ? '新增用户' : '编辑用户信息'" :visible.sync="dialogUserVisible"
				width="500px" @close="resetPojoForm" :close-on-click-modal="false">
				<el-steps v-if="isAddNew" :active="active" align-center class="addusersteps" finish-status="success">
					<el-step title="添加用户信息"> </el-step>
					<el-step title="选择用户管理网点"></el-step>
					<el-step title="选择用户管理区域"></el-step>
				</el-steps>
				<div v-show="active == 0">
					<el-form :inline="true" :model="searchMap">
						<el-form-item>
							<el-input v-model="searchMap.name" @keydown.enter.native="searchEnter"
								onkeypress="if(event.keyCode == 13) return false;" placeholder="请输入用户名" @input="searchInput" clearable>
							</el-input>
						</el-form-item>
						<el-form-item>
							<el-button type="primary" @click="userSearch" class="search-mr">查询</el-button>

						</el-form-item>
					</el-form>
					<div>
						<el-table ref="multipleuserTable" :data="searchtableData" @selection-change="handleuserSelectionChange"
							@sort-change="sortchange" border tooltip-effect="dark" style="width: auto; overflow: hidden" :row-key="
								(row) => {
									return row.id;
								}
							">
							<el-table-column type="selection" width="40" :reserve-selection="true">
							</el-table-column>
							<el-table-column type="index" label="序号" width="50">
							</el-table-column>
							<el-table-column prop="userName" label="用户名"> </el-table-column>
							<el-table-column prop="name" label="姓名"> </el-table-column>
							<el-table-column prop="phone" label="电话"> </el-table-column>
						</el-table>
					</div>
				</div>

				<div v-show="active == 1">
					<el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange"
						class="checkall">全选</el-checkbox>
					<div style="margin: 15px 0"></div>
					<el-tree class="Organtree" :data="OrganByCustomdata" show-checkbox default-expand-all check-on-click-node
						node-key="id" ref="Organtree" highlight-current :props="OrganBdefaultProps"
						@check="handleCheckedCitiesChange">
					</el-tree>
				</div>
				<div v-show="active == 2">
					<div v-show="orgidisnull">
						<div style="text-align: center;font-size: 0.18rem;color: #fff;margin-top: 10px;">未对用户进行公司分配，可以直接提交</div>
					</div>
					<div v-show="!orgidisnull">
						<div style="margin-top: 20px">
							<h4 style="
                  font-size: 0.16rem;
                  font-weight: 300;
                  margin-right: 10px;
                  display: inline-block;
                ">
								选择网点
							</h4>
							<el-select v-model="orgid" @change="selectaddOrganChange" placeholder="请选择">
								<el-option v-for="item in organcheckdata" :key="item.id" :label="item.name" :value="item.id">
								</el-option>
							</el-select>
						</div>
						<div style="height: 300px">
							<el-scrollbar wrap-class="scrollbar-wrapper" style="height: 100%">
								<el-tree :data="AreaTreeByOrgandata" ref="refAreaTreeByOrgandataTree" show-checkbox node-key="id"
									 :props="AreaTreeByOrganProps" @check="dialogAreaTreeByOrganChange">
									<!-- -->
								</el-tree>
							</el-scrollbar>
						</div>
						<div>
							<div style="font-size: 0.16rem; color: #fff">已选区域</div>
							<el-checkbox-group v-model="areaIdList">
								<el-checkbox v-for="item in areacheckdata" :label="item.id" :key="item.id"
									@change="editAddreacheckdata(item.id)">{{ item.name }}</el-checkbox>
							</el-checkbox-group>
						</div>
					</div>
				</div>

				<div slot="footer" class="dialog-footer">
					<el-button v-if="active != 0 && isAddNew" type="primary" @click="Previous">上一步</el-button>
					<el-button v-if="active != 2 && isAddNew" type="primary" @click="next">下一步</el-button>
					<el-button v-if="active == 2 && isAddNew" type="primary" @click="addEmployeeSubmit('pojoForm')">确 定
					</el-button>
					<el-button v-if="!isAddNew" type="primary" @click="editEmployeeSubmit('pojoForm')">确 定</el-button>
					<el-button @click="dialogUserVisible = false">取 消</el-button>
				</div>
			</el-dialog>

			<!-- 管理的区域 -->
			<el-dialog title="管理区域" :visible.sync="dialogManageAreaVisible" width="1200px" @close="clearManageAreaData"
				:close-on-click-modal="false">
				<div class="dialog-area-head">
					<h4>管理的区域</h4>
					<div>
						<el-select style="margin-right:10px" clearable size="small" v-model="Organinarea"
							@change="selectOrganainareaChange" placeholder="请选择">
							<el-option v-for="item in organOptions" :key="item.id" :label="item.name" :value="item.id">
							</el-option>
						</el-select>
						<el-button @click="dialogAddArea" size="small" type="primary">添 加</el-button>
						<el-button @click="dialogAddDelete" size="small" type="primary">移 除</el-button>

					</div>
				</div>
				<el-table :data="dialogManageAreaData" @selection-change="handleManageAreaChange" border
					style="width: 100%; margin-top: 10px" height="400px">
					<el-table-column type="selection" width="40"> </el-table-column>
					<el-table-column type="index" label="序号" width="50">
					</el-table-column>
					<el-table-column prop="organId" label="网点" width="150">
						<template slot-scope="scope">
							<div>{{ scope.row.organId | getorganName() }}</div>
						</template>
					</el-table-column>
					<el-table-column prop="areaName" label="区域" width="150">
					</el-table-column>

					<el-table-column prop="targetCategoryIds" label="电器类型">
						<template slot-scope="scope">
							<el-checkbox-group :min="1" v-model="scope.row.targetCategoryId" @change="
								(val) => {
									checkboxTargetCateGory(val, scope.row);
								}
							">
								<el-checkbox v-for="item in channelTargetCategory" :key="item.id" :label="item.id">
									{{ item.name }}
								</el-checkbox>
							</el-checkbox-group>
						</template>
					</el-table-column>
				</el-table>
				<div class="close-box">
					<el-button size="medium" type="primary" @click="dialogManageAreaVisible = false">关 闭</el-button>
				</div>
			</el-dialog>
			<el-dialog title="添加区域" :visible.sync="dialogAddAreaVisible" width="500px" @close="reGetUserBindAreaData"
				:close-on-click-modal="false">
				<div>
					<h4 style="margin-right: 20px; display: inline-block">选择网点</h4>
					<el-select v-model="dialogOrganValue" @change="selectOrganChange" placeholder="请选择">
						<el-option v-for="item in organOptions" :key="item.id" :label="item.name" :value="item.id">
						</el-option>
					</el-select>
				</div>
				<div style="height: 300px">
					<el-scrollbar wrap-class="scrollbar-wrapper" style="height: 100%">
						<el-tree :data="dialogAreaData" ref="refdialogAreaTree" show-checkbox node-key="id" :props="defaultProps"
							@check="dialogTreeChange">
						</el-tree>
					</el-scrollbar>
				</div>

				<div style="text-align: center; margin-top: 20px">
					<el-button @click="submitAddManageArea" size="medium" type="primary">确 定</el-button>
					<el-button size="medium" @click="dialogAddAreaVisible = false">取 消</el-button>
				</div>
			</el-dialog>

			<el-dialog title="编辑用户管理网点" :visible.sync="dialogEditOrganVisible" width="600px" :close-on-click-modal="false">
				<el-transfer class="shuttle-row" :titles="['未添加网点', '已添加网点']" :button-texts="['移除', '添加']"
					:props="OrganByCustomdataProps" v-model="UserBindOrgan" @change="handleEditOrganchange"
					:data="OrganByCustomdata"></el-transfer>

				<div style="text-align: center; margin-top: 20px">
					<el-button size="medium" @click="dialogEditOrganVisible = false">取 消</el-button>
				</div>
			</el-dialog>

		</div>
	</div>
</template>

<script>
import ajax from "@/utils/ajax";

import { tableSelection, deleteConfirm } from "@/utils/elementui";
import axios from "axios";

const statusOptions = [
	{ type: "N", name: "禁用" },
	{ type: "Y", name: "启用" },
];
let organOptions = [];
export default {

	data() {
		let validPassword = (rule, value, callback) => {
			if (value === "") {
				callback(new Error("密码不能为空"));
			} else {
				if (this.pojoUser.checkpassword !== "") {
					this.$refs.pojoForm.validateField("checkpassword");
				}
				callback();
			}
		};
		let validCheckPassword = (rule, value, callback) => {
			if (value === "") {
				callback(new Error("确认密码不能为空"));
			} else if (value !== this.pojoUser.password) {
				callback(new Error("两次输入密码不一致!"));
			} else {
				callback();
			}
		};
		let checkUsername = (rule, value, callback) => {
			if (!value) {
				return callback(new Error("用户名不能为空"));
			} else {
				if (this.editUsernamechecking == value && this.isAddNew == false) {
					return callback();
				} else {
					let cod = this.tableData.findIndex((item) => item.userName == value);
					if (cod != -1) {
						return callback(new Error("输入的用户名已存在"));
					} else {
						return callback();
					}
				}
			}
		};
		let checkPhone = (rule, value, callback) => {
			if (!value) {
				return callback(new Error("电话不能为空"));
			}
			if (!Number.isInteger(value)) {
				//console.log(value)
				return callback(new Error("请输入正确的电话"));
			} else {
				if (this.editphonechecking == value && this.isAddNew == false) {
					return callback();
				} else {
					let cod = this.tableData.findIndex((item) => item.phone == value);
					if (cod != -1) {
						return callback(new Error("输入的电话已存在"));
					} else {
						return callback();
					}
				}
			}
		};
		return {
			tableHeight: 300,
			editphonechecking: "",
			editUsernamechecking: "",
			tableDatachecking: [],
			permission: {
				get: true,
				modify: false,
				add: false,
				delete: false,
				group: false,
				role: false,
				area: false,

				has_role: false,
				available_role: false,
				role_add: false,
				role_delete: false,
			},
			customerId: null,
			organId: null,

			tableData: [],
			AlltableData: [],
			currentPage: 1,
			pageSize: 10,
			total: 0,
			searchMap: {
				name: "",
			},
			dialogUserVisible: false,

			pojoUser: {
				customerId: this.$store.getters.customerId,
				userName: "",
				password: "",
				manager: 0,
				checkpassword: "",
				name: "",
				phone: "",
				email: "",
			},
			rules: {
				userName: [
					{ required: true, validator: checkUsername, trigger: "blur" },
				],
				password: [
					{ required: true, message: "密码不能为空", trigger: "blur" },
					{ validator: validPassword, trigger: "blur" },
				],
				checkpassword: [
					{ required: true, message: "确认密码不能为空", trigger: "blur" },
					{ validator: validCheckPassword, trigger: "blur" },
				],
				name: [{ required: true, message: "姓名不能为空", trigger: "blur" }],
				phone: [{ required: true, validator: checkPhone, trigger: "blur" }],
				email: [
					// { required: true, message: '电子邮箱不能为空', trigger: 'blur' },
					{ type: "email", message: "请输入正确的邮箱地址", trigger: "blur" },
				],
			},
			multipleSelection: [],
			isAddNew: true,
			isUserEnable: false,

			dialogManageAreaVisible: false,
			dialogManageAreaData: [],
			alldialogManageAreaData: [],
			multipleAreaSelection: [],
			dialogAddAreaVisible: false,
			dialogOrganValue: "",
			organOptions: [],
			dialogAreaData: [],
			defaultProps: {
				children: "children",
				label: "name",
			},
			dialogAreaNodeCheck: [],
			checkedKeysArea: [],

			channelTargetCategory: [],


			//分步表单
			active: 0,
			OrganByCustomdata: [],
			OrganByCustomlenght: null,
			organIdList: [],
			organcheckdata: [],
			areaIdList: [],
			areacheckdata: [],
			OrganBdefaultProps: {
				label: "name",
			},
			AreaTreeByOrganProps: {
				children: "children",
				label: "name",
			},
			checkAll: false,
			isIndeterminate: false,
			AreaTreeByOrgandata: [],
			AreaTreeByOrgandatalength: null,
			orgid: null,
			orgidisnull: true,

			//编辑用户管理网点
			dialogEditOrganVisible: false,
			UserBindOrgan: [],
			OrganByCustomdataProps: {
				key: "id",
				label: "name",
			},
			editorganuserid: null,
			editorganusercustomerId: null,

			dialogRoleVisible: false,
			transferTitle: "",
			UserRoledata: [],
			UserBindRole: [],
			UserBindRoledataProps: {
				key: "id",
				label: "roleName",
			},
			//网点区域关系
			Organinarea: null,
			searchtableData: [],
			userSelection: []
		};
	},
	created() {
		this.customerId = this.$store.getters.customerId;
		// this.setPermission();
		this.getUserListData();
		this.getOrganByCustomdata();
		this.getUserRoledata();
		// this.getUserListDataChecking();
	},
	mounted() {
		this.$store.dispatch("actions/dynamicTitleAction", this.$route.meta.title);
		this.getTargetCategoryData();
	},
	computed: {
	},
	methods: {
		// 设置可操作的权限
		setPermission() {
			// let route_permissions = this.$route.meta.sub_permissions
			let role_permissions = this.$store.getters.rolePermissions;
			console.log(role_permissions);
			for (let item of role_permissions) {
				if (item.action === "/web/user") {
					for (let permission of item.privilegeList) {
						switch (permission.action) {
							case "/web/user/query":
								this.permission.get = true;
								break;
							case "/web/user/modify":
								this.permission.modify = true;
								break;
							case "/web/user/add":
								this.permission.add = true;
								break;
							case "/web/user/delete":
								this.permission.delete = true;
								break;
							case "/web/user/group":
								this.permission.group = true;
								break;
							case "/web/user/role":
								this.permission.role = true;
								break;
							case "/web/user/area":
								this.permission.area = true;
								break;

							default:
								break;
						}
					}
				}
			}
		},
		// 获取用户列表
		getUserListData() {
			let pocustomerId = this.customerId;
			let posearchStr = this.searchMap.name.trim();
			ajax.get({
				url: this.$API.getOrganShareRecordList,

				success: (response) => {
					//console.log(response)

					this.AlltableData = response.data;
					this.total = response.data.length;
					this.$refs.multipleTable.clearSelection();
					this.initTableData();
				},
				error: (res) => {
					//console.log(res)
					this.$message({
						message: res.message,
						type: "error",
					});
				},
			});
		},
		initTableData() {
			let pageSize = this.pageSize;
			let currentPage = this.currentPage;
			let start = (currentPage - 1) * pageSize;
			let end = start + pageSize;
			// //console.log(this.tableDataAll)
			this.tableData = this.AlltableData.slice(start, end);
			this.$refs.multipleTable.clearSelection();
			// //console.log(this.tableData)
		},
		//
		handleSizeChange(value) {
			this.pageSize = value;
			this.initTableData();
		},
		handlePageChange(value) {
			this.currentPage = value;
			this.initTableData();
		},
		//
		sortchange(column) {
			let prop = column.prop;
			let order = column.order;
			let self = this;

			if (order == "ascending") {
				switch (prop) {
					case "manager":
						this.$nextTick(() => {
							self.AlltableData = self.AlltableData.sort((n1, n2) => {
								return n1.manager - n2.manager;
							});
						});

						break;
					case "lastQuota":
						this.$nextTick(() => {
							self.AlltableData = self.AlltableData.sort((n1, n2) => {
								return n1.lastQuota - n2.lastQuota;
							});
						});
						break;
					default:
						break;
				}
			} else if (order == "descending") {
				switch (prop) {
					case "manager":
						this.$nextTick(() => {
							self.AlltableData = self.AlltableData.sort((n1, n2) => {
								return n2.manager - n1.manager;
							});
						});

						break;
					case "lastQuota":
						this.$nextTick(() => {
							self.AlltableData = self.AlltableData.sort((n1, n2) => {
								return n2.lastQuota - n1.lastQuota;
							});
						});
						break;
					default:
						break;
				}
			}
			self.initTableData();
		},

		// 点击查询
		onSearchSubmit() {
			if (this.searchMap.name.trim() === "") {
				return;
			}
			this.currentPage = 1;
			this.userSearch();
			this.$nextTick(() => {
				this.$refs.multipleuserTable.clearSelection();
				this.userSelection=[]
			});
		},
		searchInput(value) {
			if (value.trim() === "" && value.length === 0) {
				this.userSearch();
				this.$nextTick(() => {
					this.$refs.multipleuserTable.clearSelection();
				});
			}
		},
		searchEnter(e) {
			let keyCode = e.keyCode;
			if (keyCode == 13) {
				this.onSearchSubmit();
			}
		},
		
		// 新增
		handleAdd() {
			this.isAddNew = true;
			this.dialogUserVisible = true;

		},
		userSearch() {
			this.searchtableData = []
			if(this.searchMap.name){
			ajax.get({
				url: this.$API.getDifferentCompanyUserByName + this.searchMap.name,

				success: (response) => {
					//console.log(response)
					if (response.success) {
						this.searchtableData.push(response.data)
						this.$refs.multipleuserTable.clearSelection();
						this.userSelection=[]
					} else {
						this.$message({
							message: response.message,
							type: "warning",
						});
					}
				},
				error: (response) => {
					this.$message({
						message: response.message,
						type: "error",
					});
				},
			});
		}
		},
		// 新增提交
		addEmployeeSubmit() {
			let self =this
			axios
				.post(this.$API.saveOrganShareRecordWithUserTarget + this.userSelection[0].id, this.areaIdList)
				.then(function (res) {
					if (res.data.success) {
						self.$message({
							message: "区域分享成功",
							type: "success",
						});
						self.$refs.multipleuserTable.clearSelection();
						self.userSelection=[]
						self.getUserListData()
						self.searchMap.name=''
						self.searchtableData=[]
						self.dialogUserVisible = false;
					}
					else{
						self.$message({
							message: res.data.message,
							type: "error",
						});
					}
				})
				.catch(function(error) {
					console.log(1)
					self.$message({
							message: error.data,
							type: "error",
						});
				})

		},

		// 编辑
		handleEdit(data) {
			this.isAddNew = false;
			if (!this.isUserEnable) {
				this.dialogUserVisible = true;
			}
			this.$nextTick(() => {
				this.pojoUser.id = data.id;
				this.pojoUser.userName = data.userName;

				this.pojoUser.name = data.name;
				this.pojoUser.manager = data.manager;

				this.pojoUser.phone = parseInt(data.phone) ? parseInt(data.phone) : "";
				this.editphonechecking = parseInt(data.phone)
					? parseInt(data.phone)
					: "";
				this.editUsernamechecking = data.userName;
				this.pojoUser.email = data.email;
				this.pojoUser.password = data.password;
			});
		},
		// 编辑提交
		editEmployeeSubmit(formName) {
			this.$refs[formName].validate((valid) => {
				if (valid) {
					ajax.post({
						url: this.$API.editUser,
						data: this.pojoUser,
						success: (response) => {
							//console.log(response)
							if (response.success) {
								this.getUserListData();

								this.dialogUserVisible = false;
								this.$message({
									message: "编辑成功",
									type: "success",
								});
							} else {
								this.$message({
									message: response.message,
									type: "warning",
								});
							}
						},
						error: (res) => {
							//console.log(res)
							this.$message({
								message: res.message,
								type: "error",
							});
						},
					});
				} else {
					//console.log('验证失败')
				}
			});
		},

		// 表单重置
		resetPojoForm() {

			this.active = 0;
			this.organIdList = [];
			this.organcheckdata = [];
			this.areaIdList = [];
			this.areacheckdata = [];
			this.AreaTreeByOrgandata = [];
			this.$refs.Organtree.setCheckedNodes([]);
			this.isIndeterminate = false;
			this.checkAll = false;
		},


		//删除
		handleDelete(data) {
			
				deleteConfirm(this).then((res) => {
					if (res) {
						ajax.post({
							url: this.$API.deleteOrganShareRecordByUserId + data.userId,
							success: (response) => {
								//console.log(response)
								if (response.success) {
									// 成功后，重新获取数据
									this.getUserListData();

									this.$refs.multipleTable.clearSelection();
									this.$message({
										type: "success",
										message: response.message,
									});
								}
							},
							error: (res) => {
								//console.log(res)
								this.$message({
									message: res.message,
									type: "error",
								});
							},
						});
					}
				});
			
		},

		// 启用/禁用

		//根据客户获取
		getUserRoledata() {
			ajax.get({
				url: this.$API.getroleList,
				success: (response) => {
					this.UserRoledata = response.data;

				},
				error: (res) => {
					//console.log(res)
					this.$message({
						message: res.message,
						type: "error",
					});
				},
			});
		},
	


		// 管理区域
		handleManageArea(data) {
			this.editorganuserid = data.userId
			this.editorganusercustomerId = data.customerId
			this.getOrganListData();


			this.dialogManageAreaVisible = true;
		},
		// 请求弹框用户已管理的区域数据
		getUserBindAreaData() {

			ajax.post({
				url: this.$API.getUserTargetByUserIdAndCustomerId + this.editorganuserid + `/${this.editorganusercustomerId}`,
				// data: { userId: poId },
				success: (response) => {
					//console.log(response)
					const resp = response.data;

					if (resp.length > 0) {

						for (let item of resp) {
							let targetCategoryIdsArr = [];
							if (item.targetCategoryList) {
								for (let i of item.targetCategoryList) {
									targetCategoryIdsArr.push(i.id);
								}
							}
							item.targetCategoryId = targetCategoryIdsArr;
						}

					}

					this.dialogManageAreaData = resp;
					this.alldialogManageAreaData = resp
					//console.log(this.dialogManageAreaData)
				},
				error: (res) => {
					//console.log(res)
					this.$message({
						message: res.message,
						type: "error",
					});
				},
			});
		},
		// 获取通道类型数据
		getTargetCategoryData() {
			ajax.get({
				url: this.$API.getDictTargetCategoryList,
				data: {},
				success: (response) => {
					//console.log(response)
					this.channelTargetCategory = response.data;
					// 
				},
				error: (res) => {
					//console.log(res)
					this.$message({
						message: res.message,
						type: "error",
					});
				},
			});
		},
		// 勾选管理区域
		handleManageAreaChange(value) {
			this.multipleAreaSelection = value;
		},
		//处理复选框选中
		checkValue(targetCategoryIds, targetCategoryDataId) {
			// //console.log(targetCategoryIds, targetCategoryDataId)
			if (targetCategoryIds === "0") {
				return true;
			}
			if (targetCategoryIds.indexOf(targetCategoryDataId) !== -1) {
				return true;
			}
		},
		// 选择电器事件
		checkboxTargetCateGory(value, rowData) {


			let po_targetCategoryIds = value.join(",");
			console.log(value, rowData)
			ajax.post({
				url: this.$API.modifUserTarget + rowData.id,
				data: {
					userId: rowData.userId,
					areaId: rowData.areaId,
					targetCategoryId: po_targetCategoryIds,
				},
				success: (response) => {
					//console.log(response)
					if (response.success) {

						this.$message({
							message: "操作成功",
							type: "success",
						});
					}
				},
				error: (res) => {
					//console.log(res)
					this.$message({
						message: res.message,
						type: "error",
					});
				},
			});
		},
		selectOrganainareaChange() {
			let all = this.alldialogManageAreaData
			this.dialogManageAreaData = this.Organinarea ? all.filter(item => item.organId == this.Organinarea) : all
		},
		clearManageAreaData() {
			this.dialogManageAreaData = [];
			this.alldialogManageAreaData = []
			this.Organinarea = null
		},
		// 添加管理的区域
		dialogAddArea() {

			if (this.organId) {
				this.getAreaListData();
			}
			this.dialogAddAreaVisible = true;
		},
		// 获取网点列表
		getOrganListData() {

			ajax.get({
				url: this.$API.getSharedUserOrganInfo + this.editorganuserid,

				success: (response) => {
					//console.log(response)

					const resp = response.data;
					if (resp.length > 0) {
						this.organOptions = resp;
						organOptions = resp;
					} else {
						this.organOptions = [];
						organOptions = []
					}
					this.getUserBindAreaData();
				},
				error: (res) => {
					//console.log(res)
					this.$message({
						message: res.message,
						type: "error",
					});
				},
			});
		},
		// 切换网点
		selectOrganChange(value) {
			this.organId = value;
			this.getAreaListData();
		},
		// 获取区域数据
		getAreaListData() {
			let po_organId = this.organId;

			ajax.get({
				url: this.$API.getAreaByOrganIdAndUserUnBind + `${po_organId}/${this.editorganuserid}`,
				success: (response) => {
					console.log(response);
					const resp = response.data;
					this.dialogAreaData = resp;
				},
				error: (res) => {
					//console.log(res)
					this.$message({
						message: res.message,
						type: "error",
					});
				},
			});
		},
		// 点击树的复选框
		dialogTreeChange() {
			let checkArr = this.$refs.refdialogAreaTree.getCheckedNodes();
			this.dialogAreaNodeCheck = checkArr;
			//console.log(checkArr)
		},
		// 点击确定添加管理区域
		submitAddManageArea() {
			let self = this
			let po_areaId = this.$refs.refdialogAreaTree.getCheckedKeys()

			//console.log('userId：', po_userId)
			//console.log('areaId', po_areaId)
			axios
				.post(this.$API.userBindTarget + this.editorganuserid, po_areaId)
				.then(function (res) {
					if (res.data.success) {
						self.dialogAddAreaVisible = false;
						self.$message({
							message: "新增成功",
							type: "success",
						});
					}
				});

		},
		// 重新获取绑定区域的数据
		reGetUserBindAreaData() {
			this.getUserBindAreaData();
		},
		// 移除管理的区域
		dialogAddDelete() {
			let self = this
			let selections = this.multipleAreaSelection;

			let selResult = tableSelection(selections, 0);
			if (selResult) {
				deleteConfirm(this).then((res) => {
					if (res) {
						if (selections.length == 1) {
							ajax.post({
								url: this.$API.userUnBindTarget + selections[0].id,
								success: (response) => {
									//console.log(response)
									this.getUserBindAreaData();
									if (response.success) {
										this.$message({
											message: "删除成功",
											type: "success",
										});
									}
								},
								error: (res) => {
									//console.log(res)
									this.$message({
										message: res.message,
										type: "error",
									});
								},
							});
						} else {
							let attr = []
							selections.forEach(data => {
								attr.push(data.id)
							})


							axios
								.post(this.$API.userUnBindTargetList, attr)
								.then(function (res) {
									if (res.data.success) {
										self.dialogAddAreaVisible = false;
										self.$message({
											message: "删除成功",
											type: "success",
										});
										self.getUserBindAreaData();
									}
								});
						}
					}
				});
			}
		},
		trusteeship(row) {
			ajax.post({
				url: this.$API.setTargetAreaDelegated,
				data: {
					userId: row.userId,
					areaId: row.areaId,
					delegated: row.delegated,
				},
				// data:{id:77},
				success: (response) => {
					this.$message({
						message: "设置成功",
						type: "success",
					});
				},
				error: (res) => {
					//console.log(res)
					row.delegated = 1;
					this.$message({
						message: res.message,
						type: "error",
					});
				},
			});
		},
		// 多选
		handleSelectionChange(val) {
			this.multipleSelection = val;
		},
		handleuserSelectionChange(val) {
			this.userSelection = val;
		},
		next() {
			let selectionArr = this.userSelection;
			//console.log(this.userSelection)
			let selResult = tableSelection(selectionArr, 0);
			switch (this.active) {
				case 0:
					if (selResult) {
						this.active++;
					}

					break;
				case 1:
					this.organIdList = this.$refs.Organtree.getCheckedKeys();
					this.organcheckdata = this.$refs.Organtree.getCheckedNodes();
					this.orgid = this.organIdList[0];
					if (this.orgid == undefined) {
						this.orgidisnull = true;
					} else {
						this.orgidisnull = false;
						this.getAreaTreeByOrgandata();
					}
					this.active++;
					break;
				case 2:
					if (this.active++ > 2) this.active = 3;
					break;
				default:
					break;
			}
		},
		Previous() {
			if (this.active-- == 0) this.active = 0;
		},
		//根据客户获取
		getOrganByCustomdata() {
			ajax.get({
				url: this.$API.getOrganByCustomId + this.customerId,
				success: (response) => {
					this.OrganByCustomdata = response.data;
					this.OrganByCustomlenght = response.data.length;
				},
				error: (res) => {
					//console.log(res)
					this.$message({
						message: res.message,
						type: "error",
					});
				},
			});
		},
		//网点全选
		handleCheckAllChange(val) {
			if (
				this.OrganByCustomlenght == this.$refs.Organtree.getCheckedKeys().length
			) {
				this.$refs.Organtree.setCheckedNodes([]);
				this.isIndeterminate = false;
				this.checkAll = false;
			} else {
				this.$refs.Organtree.setCheckedNodes(this.OrganByCustomdata);
				this.isIndeterminate = false;
				this.checkAll = true;
			}
		},
		handleCheckedCitiesChange(data, checked) {
			let chek = checked.checkedKeys.length;

			if (chek == 0) {
				this.isIndeterminate = false;
				this.checkAll = false;
			} else if (chek > 0 && this.OrganByCustomlenght != chek) {
				this.isIndeterminate = true;
				this.checkAll = false;
			} else {
				this.isIndeterminate = false;
				this.checkAll = true;
			}
		},
		//根据区域获取网点
		getAreaTreeByOrgandata() {
			ajax.get({
				url: this.$API.getUnselectedAreaTreeByOrganId +this.userSelection[0].id+"/"+ this.orgid,
				success: (response) => {
					this.AreaTreeByOrgandata = response.data;
					this.AreaTreeByOrgandatalength = response.data.length;
				},
				error: (res) => {
					//console.log(res)
					this.$message({
						message: res.message,
						type: "error",
					});
				},
			});
		},
		// 切换网点
		selectaddOrganChange(value) {
			this.orgid = value;
			this.getAreaTreeByOrgandata();
		},
		//添加区域点击区域
		dialogAreaTreeByOrganChange() {
			let areaIdList = [...this.areaIdList];
			let refAreaTreeByOrgandataTreeid =
				this.$refs.refAreaTreeByOrgandataTree.getCheckedKeys();
			areaIdList = [
				...new Set([...areaIdList, ...refAreaTreeByOrgandataTreeid]),
			];

			let refAreaTreeByOrgandataTreedata =
				this.$refs.refAreaTreeByOrgandataTree.getCheckedNodes();

			let areacheckdata = [...this.areacheckdata];
			areacheckdata = [...areacheckdata, ...refAreaTreeByOrgandataTreedata];

			areacheckdata = areacheckdata.reduce((acc, cur) => {
				if (acc.findIndex((data) => data.id == cur.id) === -1) {
					acc.push(cur);
				}
				return acc;
			}, []);

			this.areaIdList = [...areaIdList];
			this.areacheckdata = [...areacheckdata];
		},
		editAddreacheckdata(val) {
			this.$refs.refAreaTreeByOrgandataTree.setCheckedKeys(this.areaIdList);
			let index = this.areacheckdata.findIndex((data) => data.id == val);
			this.areacheckdata.splice(index, 1);
		},
		handleEditOrgan(data) {
			this.dialogEditOrganVisible = true
			this.editorganuserid = data.userId
			ajax.get({
				url: this.$API.getUserOrgan + data.userId,
				success: (response) => {
					this.UserBindOrgan = []
					if (response.data.length > 0) {
						response.data.forEach((data) => {
							this.UserBindOrgan.push(data.id)
						})
					}

				},
				error: (res) => {
					//console.log(res)
					this.$message({
						message: res.message,
						type: "error",
					});
				},
			});
		},
		handleEditOrganchange(value, direction, movedKeys) {
			// console.log(value, direction, movedKeys)
			let self = this
			//添加
			if (direction == "right") {
				axios
					.post(this.$API.userBindOrgan + this.editorganuserid, movedKeys)
					.then(function (res) {
						if (res.data.success) {
							self.$message({
								message: "网点添加成功",
								type: "success",
							});
						}
					});
			}
			//移除
			else {
				axios
					.post(this.$API.userUnBindOrgan + this.editorganuserid, movedKeys)
					.then(function (res) {
						if (res.data.success) {
							self.$message({
								message: "网点移除成功",
								type: "success",
							});
						}
					});
			}
		},

	},
	// 过滤器
	filters: {

		statusFilter(type) {
			const roleObj = statusOptions.find((obj) => obj.type === type);
			return roleObj ? roleObj.name : null;
		},
		WhtokWh(Wh) {
			if (Wh == null) {
				return "-";
			} else {
				return Wh / 1000;
			}
		},
		mintoH(min) {
			let stomin = min / 60;
			if (min < 60) {
				return min + "秒";
			} else {
				if (stomin < 60) {
					return (stomin % 60).toFixed(1) + "分钟";
				} else {
					return (
						Math.floor(stomin / 60) + "时" + (stomin % 60).toFixed(1) + "分钟"
					);
				}
			}
		},
		getorganName(id) {
			let organName = organOptions.find((obj) => obj.id === id)
			return organName ? organName.name : '--'
		}
	},
};
function twoTimeInterval(startTime, endTime) {
	// 开始时间
	// let d1 = startTime.replace(/\-/g, "/");
	let date1 = new Date(startTime);

	// 结束时间

	let date2 = new Date(endTime);

	// 时间相差秒数
	let dateDiff = date2.getTime() - date1.getTime();
	let minutes = Math.floor(dateDiff / (60 * 1000 * 60));
	return minutes;
}
</script>

<style lang="stylus" scoped>
@import '~@/assets/styles/variables.styl';

.user-container {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  padding: 0.2rem;
  overflow: auto;
  background-color: $pageBg;

  .diolog-group-table {
    display: flex;

    .dialog-group-btn {
      // width: 1rem
      padding: 0.2rem;
      display: flex;
      flex-direction: column;
      box-sizing: border-box;

      .el-button {
        margin: 0.2rem 0 0;
      }
    }
  }

  .dialog-area-head {
    display: flex;
    justify-content: space-between;
  }
}

>>> {
  .el-table__body-wrapper {
    overflow-y: auto !important;
  }

  .el-table .el-checkbox__label {
    color: #fff;
  }
}

>>>.add-user-dia {
  .el-form .el-form-item:last-child {
    margin-bottom: 0;
  }

  .el-dialog__footer {
    padding: 0 0.3rem 0.3rem;
  }
}

.close-box {
  margin-top: 0.3rem;
  text-align: center;
}

>>>.group-dia {
  .el-table {
    height: 5rem;
  }
}

.manager-row {
  display: flex;
  height: 40px;
  align-items: center;
}

>>>.addusersteps .el-step__head.is-process {
  border-color: #67C23A;
}

>>>.addusersteps .el-step__title.is-process {
  color: #fff;
}

>>>.Organtree.el-tree--highlight-current .el-tree-node.is-current>.el-tree-node__content {
  background: none !important;
  color: #fff !important;
}

>>>.checkall.el-checkbox {
  padding-left: 32px;
  margin-top: 15px;
}

>>>.checkall.el-checkbox .el-checkbox__label {
  font-size: 0.16rem;
  color: #fff;
}
>>>.shuttle-row .el-transfer-panel {
    background: none;
}

>>>.shuttle-row .el-transfer-panel__item.el-checkbox {
    color: #fff;
}
>>>.shuttle-row .el-transfer__button {
    display: block;
    margin: 0;
    width: 90px;
    margin-top: 10px;
}
.manager-row [class*=' el-icon-'] {
  color: #fff;
  font-size: 20px;
  margin-top: 4px;
  margin-left: 10px;
}
</style>
